<?php
// +----------------------------------------------------------------------
// | BhAdmin [ BhAdmin匠心打造，我们相信，每个伟大的软件都有一个伟大的故事 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2023 https://www.bhadmin.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BhAdmin并不是自由软件，未经许可不能去掉BhAdmin相关版权
// +----------------------------------------------------------------------
// | Author: BAIHU  <admin@bhadmin.cn>
// +----------------------------------------------------------------------
namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\FileService;

class FileLogic extends BackendLogic
{
    public function __construct()
    {
        $this->service = Container::get(FileService::class);
    }

    public  function getList(): array
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (!empty($param['name'])) {
            $where[] = ["name", 'like', "%{$param['name']}%"];
        }
        if (!empty($param['type'])) {
            $where[] = ["type", '=', $param['type']];
        }
        $list =  $this->service->getListPage($where, ['*'], ['id' => 'desc'], [], request()->get('limit', 10));
        if (empty($list['list'])) return $list;
        foreach ($list['list'] as &$v) {
            $v['url'] = siteUrl($v['url']);
        }
        return message($list);
    }

    public  function add($data = [])
    {
        $save['name'] = $data['name'] ?? '';
        $save['length'] = $data['length'] ?? 0;
        $save['url'] = $data['url'] ?? '';
        $save['directory'] = $data['directory'] ?? 1;
        $save['type'] = $data['type'] ?? 1;
        $save['pid'] = $data['pid'] ?? 0;
        $save['sort'] = $data['sort'] ?? 0;
        $save['mime_type'] = $data['mime_type'] ?? '';
        $save['extension'] = $data['extension'] ?? '';
        $save['adapter'] = $data['adapter'] ?? 'local';
        return message((array)  $this->service->add($save));

    }

    public  function statistics()
    {
        //获取文件数量
        $info['number'] =  $this->service->getCountByWhere(['mark' => 1]);
        $info['size'] =  $this->service->getSumByWhere('length', ['mark' => 1]);
        $info['data'] =  $this->service->getCountByGroup(['mark' => 1]);
        return message($info);
    }

    public  function rename()
    {
        $data = request()->post();
        $id = $data['id'];
        if (!$id) throw new ApiException('记录ID不能为空');
        if (empty($data['name'])) throw new ApiException('请输入名称');
        $save['name'] = $data['name'];
        $this->service->save($save, $id);
        return message();
    }
}
